<template>
  <div class="scan-container">
    <el-card title="扫码入库确认">
      <!-- 摄像头容器 -->
      <div class="camera-wrapper">
        <video ref="video" autoplay playsinline></video>
        <canvas ref="canvas" class="canvas-hidden"></canvas>
      </div>

      <!-- 解析结果 -->
      <div v-if="scanResult" class="result-card">
        <h3>入库信息确认</h3>
        <el-descriptions column="1" border>
          <el-descriptions-item label="领料单号">{{ scanResult.requisitionId }}</el-descriptions-item>
          <el-descriptions-item label="仓库ID">{{ scanResult.warehouseId }}</el-descriptions-item>
          <el-descriptions-item label="商品ID">{{ scanResult.productId }}</el-descriptions-item>
          <el-descriptions-item label="操作员工ID">{{ scanResult.employeeId }}</el-descriptions-item>
          <el-descriptions-item label="入库数量">{{ scanResult.num }}</el-descriptions-item>
          <el-descriptions-item label="计量单位ID">{{ scanResult.unitId }}</el-descriptions-item>
        </el-descriptions>
        <div class="btn-group">
          <el-button type="primary" @click="confirmStockIn">确认入库</el-button>
          <el-button @click="resetScan">重新扫描</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import jsQR from 'jsqr'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'

export default {
  data() {
    return {
      scanResult: null, // 扫码解析结果
      canvasElement: null,
      videoElement: null,
      scanning: false
    }
  },
  mounted() {
    this.canvasElement = this.$refs.canvas
    this.videoElement = this.$refs.video
    this.startCamera()
  },
  beforeUnmount() {
    this.stopCamera()
  },
  methods: {
    // 启动摄像头
    async startCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
        this.videoElement.srcObject = stream
        this.scanning = true
        this.startScan()
      } catch (err) {
        ElMessage.error('无法访问摄像头，请确保已授予权限')
        console.error('摄像头访问失败：', err)
      }
    },

    // 停止摄像头
    stopCamera() {
      this.scanning = false
      if (this.videoElement.srcObject) {
        this.videoElement.srcObject.getTracks().forEach(track => track.stop())
      }
    },

    // 开始扫描
    startScan() {
      if (!this.scanning) return

      const canvas = this.canvasElement
      const video = this.videoElement
      const ctx = canvas.getContext('2d')

      // 调整画布大小与视频一致
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight

      // 绘制视频帧到画布
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)

      // 解析二维码
      const code = jsQR(imageData.data, imageData.width, imageData.height, {
        inversionAttempts: 'dontInvert'
      })

      if (code) {
        // 解析成功，停止扫描
        this.scanning = false
        try {
          this.scanResult = JSON.parse(code.data)
          ElMessage.success('扫码成功，请确认信息')
        } catch (err) {
          ElMessage.error('二维码格式错误')
          this.resetScan()
        }
      } else {
        // 继续扫描
        requestAnimationFrame(this.startScan)
      }
    },

    // 重新扫描
    resetScan() {
      this.scanResult = null
      this.startCamera()
    },

    // 确认入库（调用后端接口）
    async confirmStockIn() {
      const loading = ElLoading.service({ text: '正在处理入库...' })
      try {
        const response = await axios.post('/api/productInput/add', {
          requisitionId: this.scanResult.requisitionId,
          warehouseId: this.scanResult.warehouseId,
          productId: this.scanResult.productId,
          employeeId: this.scanResult.employeeId,
          num: this.scanResult.num,
          unitId: this.scanResult.unitId,
          status: 3, // 已入库状态（对应ProductInput实体的status字段）
          createTime: new Date()
        })

        if (response.data.code === 200) {
          ElMessage.success('入库成功')
          this.resetScan()
        } else {
          ElMessage.error(`入库失败：${response.data.msg}`)
        }
      } catch (err) {
        ElMessage.error('接口调用失败，请重试')
        console.error('入库接口错误：', err)
      } finally {
        loading.close()
      }
    }
  }
}
</script>

<style scoped>
.camera-wrapper {
  position: relative;
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}
video {
  width: 100%;
  height: auto;
  border: 1px solid #eee;
}
.canvas-hidden {
  display: none;
}
.result-card {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}
.btn-group {
  margin-top: 20px;
  text-align: center;
}
.btn-group button {
  margin: 0 10px;
}
</style>